import React, { useState, useEffect, useRef } from "react";
import { Button, message } from "antd";
import { PageContainer } from "@ant-design/pro-layout";
import { PlusOutlined } from "@ant-design/icons";
import ProTable from "@ant-design/pro-table";
import ProForm, {
  ModalForm,
  ProFormText,
  ProFormDependency,
  ProFormSelect,
  ProFormSwitch,
  ProFormCascader,
} from "@ant-design/pro-form";
import { useModel } from "umi";

import { fetchList, add, update, updateStatus, remove } from "@/api/admin";
import {
  MECHANISM_ROLES,
  HOSPITAL_ROLES,
  INSPECTION_ROLES,
  disableStatusOptions,
  INSPECTION_ROLES_OTHER_NUMBER,
} from "@/const";
import useRemove from "@/hooks/useRemove";
import useUpdateStatus from "@/hooks/useUpdateStatus";
import { getHospitalList } from "@/api/hospital";
import UploadFile from "@/components/UploadFile";

const modalLayout = {
  labelCol: {
    span: 4,
  },
  wrapperCol: {
    span: 20,
  },
};

const Admin = () => {
  const actionRef = useRef();
  const formRef = useRef();
  const { initialState, setInitialState } = useModel("@@initialState");
  const [hospitalList, setHospitalList] = useState([]);

  const fetchHospitalList = async () => {
    const res = await getHospitalList({
      parentId: initialState?.currentUser?.hospitalId,
    });
    setHospitalList(res.data || []);
  };

  useEffect(() => {
    fetchHospitalList();
  }, []);

  // 新增和修改
  const renderModalForm = (type, record) => {
    // type 1=新增 2=修改
    const title = type === 1 ? "新增账号" : "修改账号";

    const handleAddOrUpdate = async (fields) => {
      const postData = {
        ...fields,
        id: record?.admin?.id,
        status: fields.status ? 1 : 0,
        type: fields.roleIds[0] === 3 ? 2 : "", // 当选了医院管理员type传2
      };
      if (fields.roleIds[0] === 9) {
        postData.type = 4; // 当选了医生(PC)type传4
      }

      if (fields.roleIds[0] === 4) {
        postData.type = 5; // 当选了采样员type传5
      }

      // 质控中心
      if (initialState?.currentUser?.type === 1) {
        postData.hospitalPid = initialState?.currentUser?.hospitalId;
        postData.hospitalId = fields.hospitalId;
      }

      // 医院
      if (initialState?.currentUser?.type === 2) {
        postData.hospitalPid = initialState?.currentUser?.hospitalPid;
        postData.hospitalId = initialState?.currentUser?.hospitalId;
      }

      // 检验所
      if (initialState?.currentUser?.type === 3) {
        postData.hospitalId = initialState?.currentUser?.hospitalId;
      }

      let func = add;
      if (record?.admin?.id) {
        func = update;
      }
      const res = await func(postData);
      if (res.data) {
        message.success(title + "成功");
        formRef.current?.resetFields();
        actionRef?.current.reload();
        return true; // 关闭弹框
      }
    };

    return (
      <ModalForm
        key="modal"
        formRef={formRef}
        layout="horizontal"
        {...modalLayout}
        title={title}
        width={600}
        trigger={
          type === 1 ? (
            <Button key="button" icon={<PlusOutlined />} type="primary">
              添加
            </Button>
          ) : (
            <Button
              style={{ marginRight: 10 }}
              size="small"
              key="update"
              type="primary"
            >
              修改
            </Button>
          )
        }
        modalProps={{
          destroyOnClose: true,
          onCancel: () => {
            formRef.current?.resetFields();
          },
        }}
        onFinish={async (values) => {
          return await handleAddOrUpdate(values);
        }}
        initialValues={{
          ...record?.admin,
          roleIds: record?.roles[0]?.id,
          status: record?.admin?.status == 1,
          name: record?.admin?.name,
          confirmPwd: record?.admin?.password,
        }}
      >
        {initialState.currentUser.type === 1 && (
          <ProFormSelect
            disabled={type === 2}
            name="hospitalId"
            label="医院"
            allowClear
            fieldProps={{
              options: hospitalList,
              fieldNames: {
                label: "name",
                value: "id",
              },
            }}
            rules={[{ required: true, message: "请选择医院" }]}
          />
        )}

        <ProFormSelect
          disabled={type === 2}
          name="roleIds"
          label="角色"
          allowClear
          transform={(values) => {
            return {
              roleIds: [values],
              // roleIds: initialState.currentUser.type === 3 ? values : [values],
            };
          }}
          fieldProps={{
            // mode: initialState.currentUser.type === 3 ? "multiple" : "",
            options:
              initialState.currentUser.type === 1
                ? MECHANISM_ROLES
                : initialState.currentUser.type === 2
                ? HOSPITAL_ROLES
                : INSPECTION_ROLES,
          }}
          rules={[{ required: true, message: "请选择角色" }]}
        />

        <ProFormDependency name={["roleIds"]}>
          {({ roleIds }) => {
            return (
              (INSPECTION_ROLES_OTHER_NUMBER.includes(roleIds?.[0]) ||
                INSPECTION_ROLES_OTHER_NUMBER.includes(roleIds)) && (
                <ProForm.Item
                  name="signImage"
                  label="签名"
                  rules={[{ required: true, message: "请上传签名" }]}
                >
                  <UploadFile />
                </ProForm.Item>
              )
            );
          }}
        </ProFormDependency>

        <ProFormText
          label="姓名"
          name="name"
          rules={[
            { required: true, message: "请输入姓名" },
            {
              max: 50,
              message: "最长为50位",
            },
          ]}
        />

        <ProFormText
          disabled={type === 2}
          label="账号"
          name="account"
          rules={[
            { required: true, message: "请输入账号" },
            {
              max: 50,
              message: "最长为50位",
            },
          ]}
        />
        <ProFormText
          label="电话号码"
          name="phone"
          placeholder="请输入电话号码"
          rules={[
            {
              required: true,
              message: "请输入电话号码",
            },
            {
              pattern:
                /^1(?:3\d|4[4-9]|5[0-35-9]|6[67]|7[013-8]|8\d|9\d)\d{8}$/,
              message: "电话号码格式错误",
            },
          ]}
        />
        <ProFormText.Password
          label="密码"
          name="password"
          placeholder="请输入密码"
          rules={[
            {
              required: true,
              message: "请输入密码",
            },
            {
              min: 6,
              message: "密码最短6位",
            },
            {
              max: 12,
              message: "密码最长为12位",
            },
            // {
            //   pattern: /^[a-zA-Z]\w{5,17}$/,
            //   message: "密码格式错误",
            // },
          ]}
        />
        <ProFormDependency name={["password"]}>
          {({ password }) => {
            return (
              <ProFormText.Password
                label="确认密码"
                name="confirmPwd"
                placeholder="请输入密码"
                rules={[
                  {
                    required: true,
                    message: "请输入密码",
                  },
                  {
                    validator(_, value) {
                      if (!value || password === value) {
                        return Promise.resolve();
                      }
                      return Promise.reject(new Error("两次密码不一致"));
                    },
                  },
                ]}
              />
            );
          }}
        </ProFormDependency>

        <ProFormSwitch
          name="status"
          label="状态"
          fieldProps={{
            checkedChildren: "启用",
            unCheckedChildren: "停用",
          }}
        />
      </ModalForm>
    );
  };

  const columns = [
    {
      title: "序号",
      valueType: "index",
    },
    {
      title: "姓名",
      dataIndex: "name",
      render: (_, record) => {
        return record.admin?.name;
      },
    },
    {
      title: "账号",
      dataIndex: "account",
      render: (_, record) => {
        return record.admin?.account;
      },
    },

    {
      title: "电话号码",
      dataIndex: "account",
      render: (_, record) => {
        return record.admin?.phone || "-";
      },
    },

    {
      title: initialState.currentUser.type === 3 ? "检验所" : "医院",
      dataIndex: "hospitalName",
      search: false,
      render: (_, record) => {
        return record?.admin?.hospitalName;
      },
    },
    {
      title: "角色",
      dataIndex: "roleId",
      valueType: "select",
      search: false,
      fieldProps: {
        options: MECHANISM_ROLES,
      },
      render: (_, record) => {
        return record?.roles?.[0]?.name;
      },
    },

    {
      title: "状态",
      dataIndex: "status",
      valueType: "select",
      fieldProps: {
        options: disableStatusOptions,
      },
      search: false,
      render: (_, record) => {
        return useUpdateStatus(
          updateStatus,
          record,
          actionRef,
          "admin",
          initialState?.currentUser?.type === 1 // 是否禁用
        );
      },
    },
    {
      title: "创建时间",
      dataIndex: "createTime",
      search: false,
      render: (_, record) => {
        return record?.admin?.createTime;
      },
    },
    {
      title: "操作",
      dataIndex: "option",
      valueType: "option",
      fixed: "right",
      width: 240,
      render: (_, record) => [
        renderModalForm(2, record),
        useRemove(remove, record, actionRef, {
          ids: record?.admin.id,
        }),
      ],
    },
  ];

  if (initialState?.currentUser?.type === 1) {
    columns.splice(columns.length - 1, 1);
  }

  return (
    <PageContainer>
      <ProTable
        actionRef={actionRef}
        rowKey={(record) => record.admin.id}
        search={{
          labelWidth: 60,
          defaultCollapsed: false,
        }}
        params={
          initialState.currentUser.type === 1
            ? {
                hospitalPid: initialState.currentUser.hospitalId,
              }
            : {
                hospitalId: initialState.currentUser.hospitalId,
              }
        }
        request={fetchList}
        columns={columns}
        toolBarRender={() => [
          initialState?.currentUser?.type !== 1 && renderModalForm(1),
        ]}
      />
    </PageContainer>
  );
};

export default Admin;
